﻿/// <reference path="vswd-ext_2.2.js" />
function inputStatusWindow(_default,_inputindex,_trackername) {

    var day = new Date();
    var today = day.getFullYear() + '-' + padLeft((day.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(day.getDate().toString(), "0", 2);
    var yyday = addDays(day, -1);
    var yestoday = yyday.getFullYear() + '-' + padLeft((yyday.getMonth() + 1).toString(), "0", 2) + '-' + padLeft(yyday.getDate().toString(), "0", 2);
    
    var pagesize = 15;
    var trackernamestoreloaded = false;
    var inputstoreloaded = false;
    var bynamestore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'HandlerGetByNameList'
        }),
        reader: new Ext.data.JsonReader({
            fields: [{name:'index',type:'integer'},'expression', 'alarmindex','activename','inactivename'],
            root: "data"
        }),
        autoLoad: true
    });
    
    var inputStatusCombox = new Ext.form.ComboBox({
        typeAhead: false,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        editable: false,
        store: bynamestore,
        displayField: 'expression',
        width: 100,
        valueField: 'index'
    });

    function getSelectedAlarmIndex() {
        return bynamestore.getAt(inputStatusCombox.getValue()).get('alarmindex');
    }
    
    var controltypestore = new Ext.data.SimpleStore({
        fields: ['id', 'type'],
        data: [
        ['0', _InputReportResource_Active + '->' + _InputReportResource_Inactive]
        , ['1', _InputReportResource_Inactive + '->' + _InputReportResource_Active]
        ]
    });
    
    //load tracker name
    var trackerstore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy({
            url: 'HandlerSearchTrackerName'
        }),
        reader: new Ext.data.JsonReader({
            fields: [{ name: 'trackname'}],
            root: "data"
        }),
        autoLoad:false
    });

    bynamestore.addListener('load', function(store, records) {
        trackerstore.load();
    });

    trackerstore.addListener('load', function(store, records) {
        if (_default == true) {
            trackNameCombo.setValue(_trackername);
            var alarmindex = getAlarmIndexValueFromBitIndex(_inputindex);
            var index = bynamestore.find('alarmindex', alarmindex);
            if(index != -1)
                inputStatusCombox.setValue(index);
            controlTypeCombo.setValue('0');
            searchData();
        }
    });

    var trackNameCombo = new Ext.ux.form.CheckboxCombo({
        store: trackerstore,
        mode: 'local',
        displayField: 'trackname',
        width: 200,
        valueField: 'trackname',
        enableKeyEvents: true,
        editable: true
    });

    trackNameCombo.on('keyup', function() {
        trackerstore.filter('trackname', trackNameCombo.getRawValue(), true, false);
        trackNameCombo.bindStore(trackerstore);
    });

    trackNameCombo.on('blur', function() {
        trackerstore.clearFilter();
        trackNameCombo.bindStore(trackerstore);
    });

    trackNameCombo.on('select', function() {
        bynamestore.load({
            params: {trackernames:trackNameCombo.getValue()}
        });
    });

    var fields = ["name", "byname", "firsttime", "lasttime", "firstaddress", { name: "firstlatitude", type: "float" }, { name: "firstlongitude", type: "float" }, "lastaddress", { name: "lastlatitude", type: "float" }, { name: "lastlongitude", type: "float" }, "duration", "journey"];

    var inputstatustore = new Ext.data.Store({
        proxy: new Ext.data.HttpProxy(
        {
            url: "HandlerGetInputStatusList",
            method: "POST"
        }),
        reader: new Ext.data.JsonReader(
        {
            fields: fields,
            root: "data",
            totalProperty: "totalCount"
        })
    });



    var controlTypeCombo = new Ext.form.ComboBox({
        typeAhead: false,
        mode: 'local',
        forceSelection: true,
        triggerAction: 'all',
        editable: false,
        triggerAction: 'all',
        store: controltypestore,
        displayField: 'type',
        width: 140,
        valueField: 'id'
    });

    function autoColumnName() {
        var alarmid = getSelectedAlarmIndex();
        var activeName = _InputReportResource_Active + _InputReportResource_Time;
        var inactiveName = _InputReportResource_Inactive + _InputReportResource_Time;
        var tmpactive;
        var tmpinactive;
        bynamestore.each(function(record) {
            if (record.get("alarmindex") == alarmid) {
                tmpactive = record.get('activename');
                tmpinactive = record.get('inactivename');
            }
        });
        if (tmpactive != null)
            activeName = tmpactive;
        if (tmpinactive != null)
            inactiveName = tmpinactive;

        if (controlTypeCombo.getValue() == 0) {
            grdInput.getColumnModel().setColumnHeader(2, activeName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(3, inactiveName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(4, activeName + _InputReportResource_Address);
            grdInput.getColumnModel().setColumnHeader(5, inactiveName + _InputReportResource_Address);

        }
        else {
            grdInput.getColumnModel().setColumnHeader(3, activeName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(2, inactiveName + _InputReportResource_Time);
            grdInput.getColumnModel().setColumnHeader(5, activeName + _InputReportResource_Address);
            grdInput.getColumnModel().setColumnHeader(4, inactiveName + _InputReportResource_Address);
        }
        grdInput.show();
    }

    inputStatusCombox.on('select', function() {
        var alarmid = getSelectedAlarmIndex();
        var activeName = _InputReportResource_Active + _InputReportResource_Time;
        var inactiveName = _InputReportResource_Inactive + _InputReportResource_Time;
        var tmpactive;
        var tmpinactive;
        bynamestore.each(function(record) {
            if (record.get("alarmindex") == alarmid) {
                tmpactive = record.get('activename');
                tmpinactive = record.get('inactivename');
            }
        });
        if (tmpactive != null)
            activeName = tmpactive;
        if (tmpinactive != null)
            inactiveName = tmpinactive;
        controltypestore.getAt(0).set("type", activeName + " -> " + inactiveName);
        controltypestore.getAt(1).set("type", inactiveName + " -> " + activeName);
        controlTypeCombo.setValue('0');
        autoColumnName();
    });


    controlTypeCombo.on('select', function() {
        autoColumnName();
    });
    
    var bar = new Ext.PagingToolbar({
        pageSize: pagesize,
        store: inputstatustore,
        displayInfo: true,
        beforePageText: _Alarm_Page,
        refreshTex: _Alarm_Refresh,
        displayMsg: _Alarm_Displaying,
        emptyMsg: _Alarm_Alarm_emptyMsg
    });

    var fromDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: today
    });


    var fromTimeEditor = new Ext.form.TimeField({
        value:'00:00',
        format: 'H:i',
        width: 70
    });

    var toDateEditor = new Ext.form.DateField({
        renderer: Ext.util.Format.dateRenderer('Y-m-d'),
        format: 'Y-m-d',
        value: today
    });

    var toTimeEditor = new Ext.form.TimeField({
        value:'23:59',
        format: 'H:i',
        width: 70
    });

    function searchData() {
        if (controlTypeCombo.getRawValue() != "" || inputStatusCombox.getRawValue() != "") {
            inputstatustore.load({ params: {
                fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
                totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
                inputID: getSelectedAlarmIndex(),
                trackName: trackNameCombo.getRawValue(),
                controlTypeID: controlTypeCombo.getValue(),
                byName: inputStatusCombox.getRawValue(),
                start: 0,
                limit: pagesize
                }
            });
        }
        else {
            Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
        }
    }

    var addressCb = new Ext.form.Checkbox({ checked: false });

    var tbar = new Ext.Toolbar({
        items: [
            _Alarm_TrackerName + ':',
            trackNameCombo,
            {
                xtype: 'tbseparator', width: 5
            },
            _InputReportResource_Input + ':',
            inputStatusCombox,
            {
                xtype: 'tbseparator', width: 5
            }, _InputReportResource_StatisticalMethods + ':',
            controlTypeCombo,
            {
                xtype: 'tbseparator', width: 5
            },
            _Alarm_FromTime + ':',
            fromDateEditor,
            {
                xtype: 'tbseparator', width: 5
            },
            fromTimeEditor,
            {
                xtype: 'tbseparator', width: 5
            },
            _Alarm_ToTime + ':',
            toDateEditor,
            {
                xtype: 'tbseparator', width: 5
            },
            toTimeEditor,
            '-',
             _TrackerMain_ARP,
            addressCb, '-', //_Distance_Unit+":", distanceUnitChangeComb, '-',
            {
            tooltip: { text: _TrackerMain_Search, autoHide: true },
            icon: 'images/search16.gif',
            handler: function () {
                searchData();
            }
        },
            {
                tooltip: { text: _TrackerMain_ExportToExcel, autoHide: true },
                icon: 'images/excel16.gif',
                handler: function () {
                    if (controlTypeCombo.getRawValue() != "" || inputStatusCombox.getRawValue() != "") {
                        if (!Ext.fly('inputreportexcel')) {
                            var frm = document.createElement('form');
                            frm.id = 'inputreportexcel';
                            frm.name = id;
                            frm.style.display = 'none';
                            document.body.appendChild(frm);
                        }
                        var requestaddress = false;
                        requestaddress = addressCb.getValue();
                        if (typeof (pcsaddress) != 'undefined') {
                            requestaddress = pcsaddress && addressCb.getValue();
                        }
                        Ext.Ajax.request({
                            url: 'HandlerExcel',
                            form: Ext.fly('inputreportexcel'),
                            method: 'POST',
                            params: {
                                exceltype: 'inputreport',
                                start: 0,
                                fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
                                totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
                                inputID: getSelectedAlarmIndex(),
                                trackName: trackNameCombo.getRawValue(),
                                controlTypeID: controlTypeCombo.getValue(),
                                byName: inputStatusCombox.getRawValue(),
                                timeHeader: controlTypeCombo.getRawValue(),
                                requestaddress: requestaddress ? "1" : "0"

                            },
                            isUpload: true
                        });
                    }
                    else {
                        Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
                    }
                }
            }
        ]
    });

    var trackpointsfields = ["gpstime", "latitude", "longitude", "speed", "direction", "otherinfo", { name: "stopped", type: "bool" }, "stoppedtime"];

    var trackpointstore = new Ext.data.Store({
        reader: new Ext.data.JsonReader({
            fields: trackpointsfields,
            root: "data",
            stoptime: "stoptime", //本次搜索停止时间
            end: "end"
        }),
        proxy: new Ext.data.HttpProxy({
            url: 'HandlerGetTrackPoints',
            timeout: 240000
        })

    });

    var distancestr = _Distance_Distance + "(" + _Distance_Kilometer + ")";
    if (showmiles)
        distancestr = _Distance_Distance + "(" + _TrackerMain_Miles + ")";

    var grdInput = new Ext.grid.GridPanel({
        //hidden:true,
    store: inputstatustore,
    loadMask: true,
        columns: [
                    { header: _InputReportResource_TrackerName, width: 100, sortable: true, menuDisabled: true, dataIndex: 'name' },
                    { header: _InputReportResource_Input, width: 100, sortable: true, menuDisabled: true, dataIndex: 'byname' },
                    { header: _InputReportResource_ValidTime, width: 120, sortable: true, menuDisabled: true, dataIndex: 'firsttime' },
                    { header: _InputReportResource_InvalidTime, width: 120, sortable: true, menuDisabled: true, dataIndex: 'lasttime' },
                    { header: _InputReportResource_Active + _InputReportResource_Address, width: 200, sortable: true, menuDisabled: true, dataIndex: 'firstaddress' },
                    { header: _InputReportResource_Inactive + _InputReportResource_Address, width: 200, sortable: true, menuDisabled: true, dataIndex: 'lastaddress' },
                    { header: _InputReportResource_Duration + '(' + _InputReportResource_Minutes + ')', width: 150, sortable: true, menuDisabled: true, dataIndex: 'duration' },
                    { header: distancestr, width: 150, sortable: true, menuDisabled: true, dataIndex: 'journey', renderer: function(value) {
                        if (showmiles)
                            return kilos2miles(value);
                        else
                            return value;
                        }
                    }
                ],
        width: 800,
        height: 400,
        header: false
    });
//    grdInput.addListener('rowdblclick', function(grid, rowindex, e) {
//        var trackName = inputstatustore.getAt(rowindex).get("name");
//        var record = inputstatustore.data.items[rowindex];
//        var lastaddress = inputstatustore.getAt(rowindex).get("lastaddress");
//        var win = createHistoryMapWindow(trackName + '(' + lastaddress + ')');
//        win.show(); // 显示出来
//        rmap = createMap(win.getMap(), true, null, gmapurl);
//        record.json.ParkAddress = record.json.lastaddress;
//        rmap.drawParkingPoint(record);
//    });

    grdInput.addListener('rowdblclick', function(grid, rowindex, e) {
        var trackName = inputstatustore.getAt(rowindex).get("name");
        var firsttime = inputstatustore.getAt(rowindex).get("firsttime");
        var lasttime = inputstatustore.getAt(rowindex).get("lasttime");

        trackpointstore.reload({
            params: {
                trackName: trackName,
                fromtime: firsttime,
                totime: lasttime

            },

            callback: function() {
                Ext.MessageBox.hide();
                if (trackpointstore.getCount() > 0) {
                    var rmap;
                    var butStartStop = new Ext.Button({
                        tooltip: { text: _AnimateControl_Stop, autoHide: true },
                        icon: 'images/player_pause.png',
                        handler: function() {
                            if (butStartStop.tooltip.text == _AnimateControl_Stop) {
                                rmap.stopAnimate();
                                butStartStop.setTooltip({ text: _AnimateControl_Continue, autoHide: true });
                                butStartStop.setIcon('images/player_play.png');
                            }
                            else {
                                rmap.startAnimate();
                                butStartStop.setTooltip({ text: _AnimateControl_Stop, autoHide: true });
                                butStartStop.setIcon('images/player_stop.png');
                            }

                        }
                    });
                    var tbar = new Ext.Toolbar({
                        items: [{
                            tooltip: { text: _AnimateControl_ToStart, autoHide: true },
                            icon: 'images/player_start.png',
                            handler: function() {
                                rmap.toStartPoint();
                            }
                        }, {
                            tooltip: { text: _AnimateControl_SlowDown, autoHide: true },
                            icon: 'images/player_rew.png',
                            handler: function() {
                                rmap.slowDownAnimate();
                            }
                        }, butStartStop
                               , {
                                   tooltip: { text: _AnimateControl_SpeedUp, autoHide: true },
                                   icon: 'images/player_fwd.png',
                                   handler: function() {
                                       rmap.speedUpAnimate();
                                   }
                               }, {
                                   tooltip: { text: _AnimateControl_ToEnd, autoHide: true },
                                   icon: 'images/player_end.png',
                                   handler: function() {
                                       rmap.toEndPoint();
                                   }
                               }

                                        ]

                    });

                    var win = createHistoryMapWindow(_TrackerMain_HistoryLine + '(' + trackNameCombo.getRawValue() + ')');

                    //win.tbar = tbar;
                    win.show(); // 显示出来
                    rmap = createMap(win.getMap(), true, null, gmapurl);
                    rmap._parkingTimeCap = _Alarm_ParkingTime;
                    nextwindowx += 20;
                    nextwindowy += 20;

                    rmap.setCenterbyLatLng(0,0);
                    rmap.drawAnimateHistoryLine(trackpointstore, _TrackerMain_GPSTime, _TrackerMain_Speed);


                }
                else {
                    Ext.MessageBox.buttonText.ok = _TrackerMain_OK;
                    Ext.Msg.show({
                        title: _TrackerMain_Title,
                        msg: _Message_NoDataInSelection,
                        buttons: Ext.Msg.OK,
                        animEl: 'elId',
                        icon: Ext.MessageBox.WARNING
                    });
                }
            }
        })
    });

    var inputwindow = new Ext.Window({
        title: _InputReportResource_InputStatusReport,
        layout: 'fit',
        height: 470,
        width: 1280,
        iconCls: 'report-input',
        items: grdInput,
        tbar: tbar,
        bbar: bar,
        minimizable: true,
        
        listeners: {
            'minimize': function() {
                addTaskButtonForWindow(inputwindow);
            }
        }
    });

    inputstatustore.on('beforeload', function(store) {
        inputstatustore.baseParams = {
            fromtime: fromDateEditor.getEl().dom.value + ' ' + fromTimeEditor.getEl().dom.value,
            totime: toDateEditor.getEl().dom.value + ' ' + toTimeEditor.getEl().dom.value,
            inputID: getSelectedAlarmIndex(),
            trackName: trackNameCombo.getRawValue(),
            controlTypeID: controlTypeCombo.getValue(),
            byName: inputStatusCombox.getRawValue(),
            start: 0,
            limit: pagesize
        }
    });

    var readAddressInterval1, readAddressInterval2;
    inputstatustore.on("load", function(store, records) {
        for (i = 0; i < records.length; i++) {
            var record = records[i];
            record.set("firstaddress", record.get("firstlatitude").toFixed(6) + "," + record.get("firstlongitude").toFixed(6));
            record.set("lastaddress", record.get("lastlatitude").toFixed(6) + "," + record.get("lastlongitude").toFixed(6));
        }
        if (addressCb.getValue() == true) {
            Ext.MessageBox.show({
                msg: _Alarm_LoadingAddress,
                progressText: _CustomerConfigResource_Loading,
                width: 300,
                wait: true,
                waitConfig: { interval: 2000 }
            });
            var count = store.getCount();
            if (count > 0) {
                var i = 0;
                readAddressInterval1 = window.setInterval(function() {
                    if (i == count) {
                        window.clearInterval(readAddressInterval1);
                        i = 0;
                        readAddressInterval2 = window.setInterval(function() {
                            if (i == count) {
                                window.clearInterval(readAddressInterval2);
                                Ext.MessageBox.hide();
                                i = 0;
                                return;
                            }
                            var record = store.getAt(i);
                            imap.geoCoder(record.data.lastlatitude, record.data.lastlongitude,
                                               function(address, index) {
                                                   if (address == "")
                                                       return;
                                                   else
                                                       record.set("lastaddress", address);
                                                   i += index;
                                               });
                        }, 1000);
                        return;
                    }
                    var record = store.getAt(i);
                    imap.geoCoder(record.data.firstlatitude, record.data.firstlongitude,
                                   function(address, index) {
                                       if (address == "")
                                           return;
                                       record.set("firstaddress", address);
                                       i += index;
                                   });
                }, 1000);


            }
            else {
                Ext.MessageBox.hide();
                Ext.Msg.alert(_Alarm_NoData, _Alarm_NoData);
            }
        }
    });
    inputwindow.addListener('beforeclose', function() {
        if (!Ext.isEmpty(readAddressInterval1)) {
            window.clearInterval(readAddressInterval1);
        }
        if (!Ext.isEmpty(readAddressInterval2)) {
            window.clearInterval(readAddressInterval2);
        }
    });
    inputwindow.show();

    function getAlarmIndexValueFromBitIndex(bitindex) {
        if (bitindex == 8) {
            return '1,49';
        }
        else if (bitindex == 9) {
            return '2,50';
        }
        else if (bitindex == 10) {
            return '3,51';
        }
        else if (bitindex == 11) {
            return '4,52';
        }
        else {
            return '5,53';
        }
    }
};